<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Compressor example</title>

    <link rel="stylesheet" href="">
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>
    <h1>Compressor example</h1>
    <audio controls>
      <source src="viper.ogg" type="audio/ogg">
      <source src="viper.mp3" type="audio/mp3">
      <p>Browser too old to support HTML5 audio? How depressing!</p>
    </audio>
    <button data-active="false">Add compression</button>
    <pre></pre>
  </body>
<script>
const myAudio = document.querySelector('audio');
const pre = document.querySelector('pre');
const myScript = document.querySelector('script');
const button = document.querySelector('button');
let audioCtx;

pre.innerHTML = myScript.innerHTML;

myAudio.addEventListener('play', () => {
  if(!audioCtx) {
    // Set up AudioContext
    const AudioContext = window.AudioContext || window.webkitAudioContext;
    audioCtx = new AudioContext();

    // Create a MediaElementAudioSourceNode
    // Feed the HTMLMediaElement into it
    const source = audioCtx.createMediaElementSource(myAudio);

    // Create a compressor node
    const compressor = audioCtx.createDynamicsCompressor();
    compressor.threshold.value = -50;
    compressor.knee.value = 40;
    compressor.ratio.value = 12;
    compressor.attack.value = 0;
    compressor.release.value = 0.25;


    // connect the AudioBufferSourceNode to the destination
    source.connect(audioCtx.destination);

    button.onclick = function() {
      const active = button.getAttribute('data-active');
      if(active === 'false') {
        button.setAttribute('data-active', 'true');
        button.innerHTML = 'Remove compression';

        source.disconnect(audioCtx.destination);
        source.connect(compressor);
        compressor.connect(audioCtx.destination);
      } else if(active === 'true') {
        button.setAttribute('data-active', 'false');
        button.innerHTML = 'Add compression';

        source.disconnect(compressor);
        compressor.disconnect(audioCtx.destination);
        source.connect(audioCtx.destination);
      }
    }
  }
})
  </script>

</html>
